package com.wocai.jrt.investor.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.common.PropsUtils;
import com.wocai.jrt.investor.dao.RiskDisclosureDao;
import com.wocai.jrt.investor.model.RiskDisclosure;
import com.wocai.jrt.investor.model.RiskDisclosureBean;
import com.wocai.jrt.investor.service.spi.InvestorService;
import com.wocai.jrt.investor.service.spi.RiskDisclosureService;
import com.wocai.jrt.orders.model.Orders;
import com.wocai.jrt.orders.service.spi.OrdersService;
import com.wocai.jrt.product.model.Product;
import com.wocai.jrt.product.service.spi.ProductService;
import com.wocai.jrt.utils.MyFileUtils;
import com.wocai.jrt.utils.WPS2PDFUtils;
import com.wocai.jrt.utils.WordUtils;

/**
 * 风险揭示书相关的service业务实现。
 * 
 * @author yinlei
 * @date 2016-3-10 15:19:41
 */
@Named
public class RiskDisclosureServiceImpl extends
		MyBatisServiceImpl<RiskDisclosure, RiskDisclosureBean, String> implements
		RiskDisclosureService {
	private static final Logger LOGGER = LoggerFactory.getLogger(RiskDisclosureServiceImpl.class);

	// 添加了方法后，记得改为private
	protected RiskDisclosureDao riskDisclosureDao;
	@Inject
	private OrdersService ordersServiceImpl;
	@Inject
	private ProductService productServiceImpl;
	@Inject
	private InvestorService investorServiceImpl;

	@Override
	@Inject
	public void setBaseDao(BaseDao<RiskDisclosure, RiskDisclosureBean, String> riskDisclosureDao) {
		this.baseDao = riskDisclosureDao;
		this.riskDisclosureDao = (RiskDisclosureDao) riskDisclosureDao;
	}

	@Override
	public String create(String orderId) throws Exception {
		// 获取订单详情
		Orders orderParam = new Orders();
		orderParam.setOrderId(orderId);
		Orders order = ordersServiceImpl.unique(orderParam);

		// '订单状态 1已支付2未支付3已兑付4部分支付5已取消6已完成7即将到期8带兑付'
		Integer[] states = { 2, 3, 4, 5 };
		List<Integer> stateList = new ArrayList<Integer>(Arrays.asList(states));
		if (null == order || stateList.contains(order.getState())) {
			return null;
		}

		// 获取产品详情
		Product product = productServiceImpl.get(order.getProductId());

		// 风险揭示书模板id
		String riskDisclosureId = product.getRiskDisclosureId();

		if (StringUtils.isBlank(riskDisclosureId)) {
			LOGGER.info("you need set riskDisclosure of product on jrt_org_admin");
			return null;
		}

		// 风险揭示书原件
		String riskDisclosure = riskDisclosureDao.get(riskDisclosureId).getUrl();

		// 用户（投资人）各自合并签名后的揭示书路径
		String userRiskDisclosure = null;
		if (!StringUtils.isBlank(riskDisclosure)) {
			if (riskDisclosure.toLowerCase().endsWith(".docx")) {

				Map<String, String> map = new HashMap<String, String>();

				// 基金全称
				map.put("FundFullName", order.getProductName());

				// 投资人签名，这里是图片路径
				String investorSignName = PropsUtils.get("images.url")
						+ order.getRiskDisclosureSign();
				map.put("InvestorSignName", investorSignName);
				LOGGER.info("set investorSign path success, investorSignPath=[{}]",
						investorSignName);

				// 签单时间
				String signTime = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());
				map.put("SignTime", signTime);
				LOGGER.info("create signTime success, signTime=[{}]", signTime);

				map.put("[", "");
				map.put("]", "");

				// 生成中间文件路径，中间文件不会被删除，作为备份
				String filename = new File(riskDisclosure).getName();
				String docxPath = MyFileUtils.getFilePath(filename, MyFileUtils.DOC_TYPE);

				// 生成中间文件，即替换占位符生成新的docx文件，注：contactPath带占位符合同路径，docxPath替换后中间文件路径
				WordUtils.searchAndReplace(riskDisclosure, docxPath, map);
				LOGGER.info("replace contact file success, contactPath=[{}], docxPath=[{}]",
						riskDisclosure, docxPath);

				String investorName = investorServiceImpl.get(order.getInvestorId()).getName();

				// 生成最终的pdf文件路径
				userRiskDisclosure = MyFileUtils.getFilePath(
						filename.replace(".docx", "_【" + investorName + "】.pdf"),
						MyFileUtils.PDF_TYPE);

				// 生成最终的pdf文件，即将中间文件docx转换成pdf文件即可,userContactPath:目标文件路径
				WPS2PDFUtils.word2PDF(docxPath, userRiskDisclosure);
				LOGGER.info("convert word to pdf success, docxPath=[{}], userContactPath=[{}]",
						docxPath, userRiskDisclosure);

				// 更新订单合同编号
				Orders orderData = new Orders();

				// 这里不是orderId而是id
				orderData.setId(order.getId());
				orderData.setRiskDisclosure(userRiskDisclosure);
				orderData.setRiskDisclosureId(riskDisclosureId);
				ordersServiceImpl.updateById(orderData);
				LOGGER.info(
						"update order orderContactNum success,  orderId=[{}], userRiskDisclosure=[{}]",
						orderId, userRiskDisclosure);
			} else {
				LOGGER.error("not support other file format but docx, userContactPath=[{}]",
						userRiskDisclosure);
			}
		}

		return userRiskDisclosure;
	}
}
